package pers.mobian.myblog.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import pers.mobian.myblog.pojo.Comment;
import pers.mobian.myblog.pojo.User;
import pers.mobian.myblog.service.BlogService;
import pers.mobian.myblog.service.CommentService;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {


    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;


    @Value("$(comment.avatar)")
    private String avatar;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {
        System.out.println("+++++++++++++++++++++++");
        System.out.println("+++++++++++++++++++++++");
        model.addAttribute("comments", commentService.listCommentByBlogId(blogId));
        return "blog :: commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session) {

        User user = (User) session.getAttribute("user");
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlog(blogId));

        if (user != null) {
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
            //由于我们前端是含有nickname的，所以，这里可以不用传入昵称
//            comment.setNickname(user.getNickname());


        } else {
            comment.setAvatar(avatar);
        }
        commentService.saveComment(comment);
        System.out.println("=============");
        return "redirect:/comments/" + comment.getBlog().getId();
    }

}
